<script setup lang="ts">
import { onMounted, ref } from 'vue'
import Post from '@/components/post/index.vue'
// 引入 Element Plus 组件
import { ElTabs, ElTabPane, ElLoading } from 'element-plus'
import { usePostStore } from '@/stores/modules/post'
import { useRoute } from 'vue-router'
import 'element-plus/dist/index.css'

// 定义 Post 数据类型
interface PostItem {
  post: {
    pictureBase64: string
    title: string
    content: string
    publishTime: string
    commentCount: number
    id: number
    userId: number
    readPermission: number
    commentPermission: number
  }
  userName: string
}

const postStore = usePostStore()
const route = useRoute()

// 定义查询类型，默认查询文章
const searchType = ref('article')

const posts = ref<PostItem[]>([])

const keywords = route.query.keyword as string

onMounted(() => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  setTimeout(() => {
    loading.close()
    handleTabClick()
  }, 2500)
})

// 处理选项卡点击事件
const handleTabClick = () => {
  setTimeout(() => {
    console.log(`当前查询类型：${searchType.value}`)
    // 这里可以添加查询逻辑
    if (searchType.value === 'article') {
      posts.value = postStore.getPostsByTitleAndContent(
        keywords,
      ) as PostItem[]
    } else if (searchType.value === 'title') {
      posts.value = postStore.getPostsByTitle(
        keywords,
      ) as PostItem[]
    } else if (searchType.value === 'user') {
      posts.value = postStore.getPostsByUsername(
        keywords,
      ) as PostItem[]
    }
    console.log(posts.value)
  })
}
</script>

<template>
  <div>
    <!-- 查询类型选择，改为选项卡形式 -->
    <div class="type-select">
      <el-tabs
        v-model="searchType"
        @tab-click="handleTabClick"
      >
        <el-tab-pane
          label="文章"
          name="article"
        ></el-tab-pane>
        <el-tab-pane
          label="标题"
          name="title"
        ></el-tab-pane>
        <el-tab-pane label="用户" name="user"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- 渲染查询结果 -->
    <Post
      v-for="(post, index) in posts"
      :key="index"
      :postData="{
        // 添加空值检查和默认值
        cover: post.post?.pictureBase64 || '',
        username: post.userName || '',
        title: post.post?.title || '',
        desc: post.post?.content?.substring(0, 10) || '',
        publishTime: post.post?.publishTime || '',
        commentCount: post.post?.commentCount || 0,
        id: post.post?.id || -1,
        userId: post.post?.userId || -1,
      }"
      :permission="{
        read: post.post.readPermission,
        comment: post.post.commentPermission,
      }"
    />
  </div>
</template>

<style lang="scss" scoped></style>
